<?php

class userData extends bee\form
{ protected static $__formID = "frm200911221141";
  protected $client;
  protected $client_ext;

  protected $error;
  protected $viewRights;
  protected $managePermissions;
  protected $manageLimits;

  protected $arr_kom;
  protected $arr_grp;
  protected $arr_limit;
  protected $arrStat;

  protected $txtId;
  protected $txtLogin;
  protected $txtFname;
  protected $txtLname;
  protected $password;
  protected $optStatus;
  protected $lblLastLoginDate;
  protected $optRegion;
  protected $optSector;
  protected $txtDescription;
  protected $txtCity;
  protected $txtAddress;
  protected $optViewRights;
  protected $optCustomer;


  public function createForm($evt)
  {
    $this->__caption = "User data";
    $this->__version = "1.1f";
    $this->__activeMenu = "userAdministration";

    $this->client = new bee\user();
	  $this->client_ext = new user_ext();
	  $this->error = new bee\serror();

    if(isset($evt["id"]))
    { if(bee\ownsClient($evt["id"]))
	    { $this->client->SELECT($evt["id"]);
	      $this->client_ext->SELECT($evt["id"]);
	      $this->client->password = "";
	    } else
	    { bee\processor::denyUser();
	    }
    }

    $this->managePermissions   = bee\owns_acces($this->__app->getUser()->id, "userData", "permit");
    $this->manageLimits        = bee\owns_acces($this->__app->getUser()->id, "userData", "limit");
    $this->arrStat = bee\getListByRange(1);
    $this->viewRights = bee\getListByRange(10);

    $customer = new bee\org_unit();
    $rsCust = new bee\rowSet($customer, new bee\afterWhere(" ORDER BY name "));

    $region = new region();
    $rsReg = new bee\rowSet($region);

    $sector = new sector();
    $rsSec = new bee\rowSet($sector);

    $this->txtId            = new bee\text("id",            $this->client->id);
    $this->txtLogin         = new bee\text("login",         $this->client->login);
    $this->txtFname         = new bee\text("fname",         $this->client_ext->fname);
    $this->txtLname         = new bee\text("lname",         $this->client_ext->lname);
    $this->password         = new bee\text("password",      $this->client->password);
    $this->optStatus        = new bee\option("staatus",     $this->client->status, $this->arrStat);
    $this->optStatus->notSelectedValue = null;
    $this->optStatus->notSelectedText = null;
    $lld = bee\YMDdmy($this->client->last_login_date);
    $this->lblLastLoginDate = new bee\label("llDate", $lld);
    $this->optRegion        = new bee\option("region",      $this->client_ext->region, $rsReg, "name");
    $this->optRegion->notSelectedText= "choose region";
    $this->optSector        = new bee\option("sector",      $this->client_ext->sector, $rsSec, "name");
    $this->optSector->notSelectedText= "choose sector";
    $this->txtDescription   = new bee\text("description",   $this->client->description);
    $this->txtCity          = new bee\text("city",          $this->client_ext->city);
    $this->txtAddress       = new bee\text("address",       $this->client_ext->address);
    $this->optViewRights    = new bee\option("view_rights", $this->client->view_rights, $this->viewRights);
    $this->optViewRights->notSelectedValue = null;
    $this->optViewRights->notSelectedText = null;
    $this->optCustomer      = new bee\option("customer",    $this->client->org_id, $rsCust, "name");
    $this->optCustomer->notSelectedValue = null;

    $this->getUserGroups();
  }

  public function drawForm($evt)
  { $this->__DSDoc->setVariable("manage_permissions", $this->managePermissions);
    $this->__DSDoc->setVariable("manage_limits",      $this->manageLimits);
    $this->__DSDoc->setRow($this->client);
    $this->__DSDoc->setRow($this->client_ext);
    $this->__DSDoc->setTableFromArr($this->arr_grp, "grupa");

  }

  public function add($evt)
  { $cfg = bee\config::getInstance();

    $this->client->fillFromArray();
    $this->client_ext->fillFromArray($evt);
  	$this->client->status = $evt["staatus"];
  	$this->client->org_id = $evt["customer"];

    if($this->__app->getClientFilter())
    { $this->client->org_id =  bee\app::$user->org_id;
      $this->client->view_rights = 1;
    }

    if(!$this->validate($this->client, $this->error))
    { $this->__app->setMessage($this->error->err_description, MSG_LEVEL_ERROR);
    } else
    { if($cfg->sys_ENCRYPT_PASS)
      { $client->password = sha1($client->password);
      }
      $this->client->INSERT();
      $this->client_ext->id = $this->client->id;

      $this->client_ext->INSERT();
      $gr_usr = new bee\gr_usr();
      $gr_usr->group_id = 3;
      $gr_usr->user = $this->client->id;
      $gr_usr->INSERT();
      $this->__app->setMessage("User added");
      $this->getUserGroups();
    }
  }

  public function update($evt)
  { $cfg = bee\config::getInstance();
    if(!bee\ownsClient($evt["id"]))
    { bee\denyUser();
    }
    $this->client->fillFromArray($evt);
  	$this->client_ext->fillFromArray($evt);

  	$this->client->status = $evt["staatus"];
  	$this->client->org_id = $evt["customer"];

    if(!$this->validate($this->client, $this->error))
    { bee\app::setMessage($this->error->err_description, MSG_LEVEL_ERROR);
    } else
    { if($cfg->sys_ENCRYPT_PASS)
      { $this->client->password = sha1($this->client->password);
      }
      $this->client->UPDATE();
      $this->client_ext->UPDATE();
      $this->__app->setMessage("User data modified.");
    }
  }

  public function delete($evt)
  { $cfg = bee\config::getInstance();
    try
    { $this->client->fillFromArray();
			$this->client->SELECT($evt["id"]);
      if(!bee\ownsClient($this->client->id))
      { die("bee\denyUser();");
      	bee\denyUser();
      }

//      $promet->client = $this->client->id;
//      $rs_promet = new bee\rowSet($promet);
//      $db = bee\db::getInstance();

      $del_msg = "User \"" . $this->client->login . "\" deleted";
      $allow_del = true;
/*
      if($rs_promet->getRow())
      { $allow_del = false;
        $del_msg = "User\"" . $this->client->login . "\" can't be deleted because it has generated traffic.";
      } else
      { $protocol = new bee\protocol();
        $protocol->who = $this->client->id;
        $rs_protocol = new bee\rowSet($protocol);
        if($rs_protocol->getRow($protocol))
        { $allow_del = false;
          $del_msg = "User\"" . $this->client->login . "\" can't be deleted because it has generated protocols.";
        }
      }
*/
      if($allow_del)
      { $this->client->DELETE();
        $this->client_ext->DELETE();
        /*
        $limit_client = new limit_client();
        $limit_client->client = $this->client->id;
        $limit_client->tip = 1;
        $rs_limit_client = new bee\rowSet(clone $limit_client);
        while($rs_limit_client->getRow($limit_client))
        { $limit_client->DELETE();
        }
          */
        $gr_usr = new bee\gr_usr();
        $gr_usr->user  = $this->client->id;
        $rs_gr_usr = new bee\rowSet(clone $gr_usr);
        while($rs_gr_usr->getRow($gr_usr))
        { $gr_usr->DELETE();
        }
      }

      $this->__app->setMessage($del_msg, MSG_LEVEL_WARNING);
    } catch(Exception $e)
    { $this->__app->setMessage($e->getMessage(), MSG_LEVEL_ERROR);
    }
    $header = "Location: " . $cfg->sys_site_name . "/index.php?__form=" . $this->__parent . "&sys_msg=" . trim($this->__app->getMessageText()) . "&sys_msg_style=" . $this->__app->getMessageLevel();
    header($header);
  }

  public function permit($evt)
  { global $sys_msg;
    global $sys_msg_style;

    if(isset($evt["id"]) ? $evt["id"] : "")
    { bee\db::getInstance()->beginTransaction();
      try
      { if(!bee\ownsClient($evt["id"]))
        { bee\denyUser();
        }
        $this->client->SELECT($evt["id"]);
        $gr_usr = new bee\gr_usr();
        $gr_usr->user = $this->client->id;
        $rs = new bee\rowSet(clone $gr_usr);
        while ($rs->getRow($gr_usr))
        { $gr_usr->DELETE();
        }

        if(isset($evt["group"]) ? $evt["group"] : "")
        { foreach ($_REQUEST["group"] AS $group)
          { $gr_usr = new bee\gr_usr();
            $gr_usr->user = $this->client->id;
            $gr_usr->group_id = $group;
            $gr_usr->INSERT();
          }
        }

        bee\db::getInstance()->commit();
        $this->getUserGroups();
        $this->__app->setMessage("User's rights changed.", MSG_LEVEL_NORMAL);

      } catch(Exception $e)
      { $this->__app->setMessage($e->__toString(), MSG_LEVEL_ERROR);
        bee\db::getInstance()->rollBack();
      }
    } else
    { $this->__app->setMessage("There's no user ID.", MSG_LEVEL_ERROR);
    }
  }

  /**
   * @todo in this version limits ara not implemented (updated) yet
   * Enter description here ...
   * @param unknown_type $evt

  public function limit($evt)
  { if(isset($evt["id"]) ? $evt["id"] : "")
    { bee\db::getInstance()->beginTransaction();
      try
      { if(!bee\ownsClient($evt["id"]))
        { bee\denyUser();
        }
        $this->client->SELECT($evt["id"]);
        $limit_client = new limit_client();
        $limit_client->client = $this->client->id;
        $limit_client->tip = 1;
        $rs_limit_client = new bee\rowSet($limit_client);
        while ($rs_limit_client->getRow($limit_client))
        { $limit_client->DELETE();
        }
        if(isset($evt["limit"]) ? $evt["limit"] : "")
        { foreach ($_REQUEST["limit"] AS $limit)
          { $limit_client = new limit_client();
            $limit_client->client = $this->client->id;
            $limit_client->limit = $limit;
            $limit_client->tip = 1;
            $limit_client->INSERT();
          }
        }
        bee\db::getInstance()->commit();
        $sys_msg = "User's limits changed";
        $sys_msg_style = "note";
      } catch(Exception $e)
      { $sys_msg = $e->__toString();
        $sys_msg_style = "error";
        bee\db::getInstance()->rollBack();
      }
    } else
    { $sys_msg = "There's no user ID";
      $sys_msg_style = "error";
    }
  }
*/

	protected function validate(bee\user $row, bee\serror &$error)
	{ $cfg = bee\config::getInstance();
	  if(!$row->login)
	  { $error->err_code = -10;
	    $error->err_description .= "\nLogin is necessary.";
	    return false;
	  }
	  if(strlen($row->password) > 0 && strlen($row->password) < $cfg->app_PASS_LENGTH)
	  { $error->err_code = -11;
	    $error->err_description .= "\nPassword must be at least " . $cfg->app_PASS_LENGTH . " character long";
	    return false;
	  }
	  if(strlen($row->password) < $cfg->app_PASS_LENGTH && $_REQUEST["sys_action"] == "add")
	  { $error->err_code = -12;
	    $error->err_description .= "\nPassword must be at least " . $cfg->app_PASS_LENGTH . " character long";
	    return false;
	  }
	  $old_client = new bee\user();
	  $old_client->login = $row->login;
	  $rs_client = new bee\rowSet($old_client);
	  if($rs_client->getRow($old_client) && $old_client->id != $row->id)
	  { $error->err_code = -20;
	    $error->err_description .= "There's already user with given username.";
	    return false;
	  }
	  $error->err_code = 0;
	  return true;
  }
  private function getUserGroups()
  { $this->arr_grp   = array();
    $group           = new bee\group();
    $rsGroup         = new bee\rowSet($group);

    while($rsGroup->getRow($group))
    { $gr_usr            = new bee\gr_usr();
      $gr_usr->user      = $this->client->id;
      $gr_usr->group_id  = $group->id;
      $rs_gu =    new bee\rowSet(clone $gr_usr);
      if($rs_gu->getRow($gr_usr))
      {
        $group->checked = "true";
      } else
      { $group->checked = "false";
      }
      $this->arr_grp[] = clone $group;
    }
  }
}
